#include "clipboardStorage.h"
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QTextStream>
#include <QApplication>
#include <QDebug>
#include <QBuffer>
#include <QDir>
#include <QFileInfo>
#include <QStandardPaths>
using namespace std;

ClipboardStorage::ClipboardStorage(QObject *parent) : QObject(parent), items() {

}

ClipboardStorage::~ClipboardStorage() {

}

// 添加剪贴板项
void ClipboardStorage::addItem(const ClipboardItem& item) {
    items.insert(items.begin(), item);
}

void ClipboardStorage::addFileItem(const ClipboardItem& item) {
    // 获取原文件完整路径
    QString sourceFilePath = item.getDisplayText();
    QFileInfo sourceFile(sourceFilePath);

//    // 检查文件是否存在且是一个文件
//    if (!sourceFile.exists()||!sourceFile.isFile()) {
//        qDebug() << "File does not exist or is not a file:" << sourceFilePath;
//        return;
//    }
    // 获取当前项目文件夹路径
    QString projectFolderPath = QApplication::applicationDirPath();
    QString tempFolderPath = QDir(projectFolderPath).filePath("tempFileStorage");
    QDir tempDir(tempFolderPath);

    // 如果 tempFileStorage 文件夹不存在，则创建它
    QString storageFolderPath = tempFolderPath;
    if (!QDir(storageFolderPath).exists()) {
        QDir().mkpath(storageFolderPath);
    }

    // 创建目标文件路径
    QString destinationFilePath = QDir(storageFolderPath).filePath(sourceFile.fileName());

    // 复制文件到临时文件夹
    if (sourceFile.isFile()&&QFile::copy(sourceFilePath, destinationFilePath)) {
        qDebug() << "File copied to tempFileStorage:" << destinationFilePath;
    }
    else if (sourceFile.isDir()&&ClipboardStorage::copyDirectory(sourceFilePath, destinationFilePath)){
        qDebug() << "Directory copied to tempFileStorage:" << destinationFilePath;
    }
    else {
        qDebug() << "Failed to copy file or directory to tempFileStorage:" << destinationFilePath;
    }
    items.insert(items.begin(), item);
}

// 辅助函数，递归复制文件夹
bool ClipboardStorage::copyDirectory(const QString &sourceDirPath, const QString &destinationDirPath) {
    QDir sourceDir(sourceDirPath);
    if (!sourceDir.exists()) {
        qDebug() << "Source directory does not exist:" << sourceDirPath;
        return false;
    }

    QDir destinationDir(destinationDirPath);
    if (!destinationDir.exists()) {
        // 创建目标目录
        if (!destinationDir.mkpath(".")) {
            qDebug() << "Failed to create destination directory:" << destinationDirPath;
            return false;
        }
    }

    QStringList files = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
    for (const QString &file : files) {
        QString srcFilePath = sourceDir.path() + "/" + file;
        QString destFilePath = destinationDir.path() + "/" + file;

        if (QDir(srcFilePath).exists()) {
            // 如果是目录，则递归复制
            if (!copyDirectory(srcFilePath, destFilePath)) {
                return false;
            }
        } else {
            // 如果是文件，则直接复制
            if (!QFile::copy(srcFilePath, destFilePath)) {
                qDebug() << "Failed to copy file to tempFileStorage:" << destFilePath;
                return false;
            }
        }
    }
    return true;
}

void ClipboardStorage::favoriteItem(size_t index) {
    bool localIsFavorite = items[index].isFavorite();
    items[index].setFavorite(localIsFavorite == true ? false : true);
}



// 获取所有剪贴板项
vector<ClipboardItem> ClipboardStorage::getItems() {
    vector<ClipboardItem> result;
    for (const auto& item : items) {
        result.push_back(item);
    }
    return result;
}



// 导出剪贴板数据为 JSON 文件
void ClipboardStorage::exportData(const QString& filePath) {
    QJsonArray jsonArray;
    for (const auto& item : items) {
        QJsonObject jsonObject;
        jsonObject["type"] = static_cast<int>(item.getType());
        if(item.getType()==ClipboardType::Image){
            QImage image;
            // 获取图像内容并转换为 Base64
            image = item.getContent().value<QImage>();
            QByteArray byteArray;
            QBuffer buffer(&byteArray);
            buffer.open(QIODevice::WriteOnly);
            image.save(&buffer, "PNG"); // 可以选择其他格式，例如 "JPEG"
            jsonObject["content"] = QString(byteArray.toBase64());
        }else{
            jsonObject["content"] = item.getContent().toString();
        }

        jsonObject["favorite"] = item.isFavorite();
        jsonArray.append(jsonObject);
    }

    QJsonDocument jsonDoc(jsonArray);
    QFile file(filePath);
    if (!file.open(QIODevice::WriteOnly)) {
        qDebug() << "Could not open file for writing:" << filePath;
        return;
    }
    file.write(jsonDoc.toJson());
    file.close();
    qDebug() << "Data exported to" << filePath;
}

// 导入剪贴板数据从 JSON 文件
void ClipboardStorage::importData(const QString& filePath) {
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Could not open file for reading:" << filePath;
        return;
    }

    QByteArray jsonData = file.readAll();
    file.close();

    QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData);
    if (!jsonDoc.isArray()) {
        qDebug() << "Invalid JSON format.";
        return;
    }

    items.clear();
    QJsonArray jsonArray = jsonDoc.array();
    for (const auto& value : jsonArray) {
        QJsonObject obj = value.toObject();
        ClipboardType type = static_cast<ClipboardType>(obj["type"].toInt());
        QVariant content;

        if (type == ClipboardType::Image) {
          // 从 Base64 字符串创建 QImage
            QString base64String = obj["content"].toString();
            QByteArray byteArray = QByteArray::fromBase64(base64String.toUtf8());
            QImage image;
            image.loadFromData(byteArray);
            content = QVariant::fromValue(image);

         } else {
            content = obj["content"].toString();
         }

        ClipboardItem item(type, content);
        item.setFavorite(obj["favorite"].toBool());
        items.push_back(item);
    }
    qDebug() << "Data imported from" << filePath;
}

// 删除项目
void ClipboardStorage::removeItem(size_t index) {
    if (index < items.size()) {
        items.erase(items.begin() + index);
        qDebug() << "Item at index" << index << "removed.";
    } else {
        qDebug() << "Index out of bounds for removal.";
    }
}

// 编辑项目内容
bool ClipboardStorage::editItem(size_t index, const QVariant& newContent) {
    if (index < items.size()) {
        if (newContent == (items[index].getContent())) {
            return true;
        }
        bool b = items[index].setContent(newContent);
        if(b) {
            emit updateItem();
            QCoreApplication::processEvents();
        }
        return b;
    }
    qDebug() << "Index out of bounds for editing.";
    return false;
}



size_t ClipboardStorage::getItemIndex(const ClipboardItem &item) {
    vector<ClipboardItem>::iterator result = find(items.begin(), items.end(), item);
    return distance(items.begin(), result);
}
